import utils from "./utils.js";
import config from "./config.js";
import Request from "./request.js";

const install = (Vue, vm) => {
    // 挂载请求 (如果要用多个域名的请求只需要多添加拦截器即可)
    Vue.prototype.$request = new Request();
    // 设置请求全局配置
    Vue.prototype.$request.setConfig({
        baseUrl: config.baseUrl,
    });

    // 请求拦截
    Vue.prototype.$request.config.requestIntercept = (request) => {
        // 设置请求token
        request.header.token = vm.token;

        // 微信小程序设置appid
        // #ifdef MP-WEIXIN
        request.header.appid = vm.manifest['mp-weixin'].appid;
        // #endif

        // 日志打印
        utils.reqlog(request);
        // 请求加密
        // utils.reqMd5(request);

        return request;
    };
    // 响应拦截
    Vue.prototype.$request.config.responseIntercept = (response, options) => {
        // 响应成功
        if (response.success) {
            if (response.data && response.data.logId) {
                vm.$store.commit('setState', {
                    name: 'logid',
                    data: response.data.logId
                })
            }
            return response;
        } else if (options.handleError) {
            // 如果接口响应错误就进入自定义错误逻辑处理
            console.log('request', response.respCode)
            switch (response.respCode) {
                case '0000':
                    uni.showToast({
                        title: response.respMsg,
                        icon: 'none',
                        duration: 2000,
                        success: () => {}
                    });
                    break;
                case '1000':
                case '1001':
                    uni.showToast({
                        title: response.respMsg,
                        icon: 'none',
                        duration: 2000,
                        success: () => {
                            vm.$store.commit('closeApp');
                            // 如果是微信小程序就显示授权
                            // #ifdef MP-WEIXIN
                            let pageId = vm.$getState('pageId');
                            setTimeout(() => {
                                uni.$emit(`auth-login-${pageId}`, {});
                            }, 1000)
                            // #endif
                            // #ifndef MP-WEIXIN
                            uni.reLaunch({
                                url: '/pages/login/auth'
                            });
                            // #endif
                        }
                    });
                    break;
                default:
                    uni.showModal({
                        title: '提示',
                        content: response.respMsg || '网络错误,' + response.respCOde,
                        showCancel: false,
                        success: () => {}
                    });
                    break;
            }
        }
    }
}

export default {
    install
}
